<?php


namespace app\common\business;


use app\common\lib\ZhyxMongo;
use app\common\model\CollectClass;
use app\common\model\PatientInfo;
use app\common\model\ServiceItem;
use catcher\exceptions\FailedException;
use MongoDB\BSON\ObjectId;
use think\Exception;
use think\exception\HttpException;

class Contract
{
    protected $commonDomain = null;
    protected $model = null;

    public function __construct()
    {
        $this->commonDomain = new Common();
        $this->model = new \app\common\model\Contract();
    }

    public function createData(array $data)
    {
        //根据传过来的日期判断该患者是否已经签约了
        $isContract = $this->model->where([
            ["his_id", "=", $data["his_id"]],
            ["status", "<>", 1003],
            ["service_start_date", "<", $data["service_end_date"]],
            ["service_end_date", ">", $data["service_start_date"]]
        ])->count();

        if ($isContract > 0) {
            throw new FailedException("时间重叠，不能创建签约");
        }
        //根据患者ID获取患者信息
        $patientInfo = (new PatientInfo())->getInfo($data["his_id"], ["patientId", "name", "sex", "inage", "accountphone"])->toArray();

        $data = array_merge($data, $patientInfo);
        $data["status"] = 1000;

        //执行入库操作
        return $this->model->createBy($data);

    }

    public function modifyData($id, $data)
    {
        return $this->model->updateBy($id, $data);
    }


    public function getListByPatientId(string $patientId, int $limit = 15)
    {

        $result = $this->model->where("his_id", "=", $patientId)->order("id", "desc")->paginate($limit);
        if (count($result->items()) > 0) {
            $result = $result->append(["status_text"]);
        }

        return $result;
    }

    public function attention(int $uid, string $id, int $type)
    {

        if ($type === 2) {
            $result = ZhyxMongo::getInstance()->setCollection("contract")->updateOne(["_id" => new ObjectId($id)], ['$pull' => ['attention' => $uid]]);
        } else {
            $result = ZhyxMongo::getInstance()->setCollection("contract")->updateOne(["_id" => new ObjectId($id)], ['$push' => ['attention' => $uid]]);
        }
        return $result;

    }

    public function grouping(array $patientList, string $groupId, int $creatorId, int $type = 2): bool
    {

        if ($groupId !== "-2" && $groupId !== "-1") {
            //判断分组ID是否存在
            $groupInfo = (new CollectClass())->findBy($groupId);
            if (empty($groupInfo)) {
                throw new FailedException("分组不存在");
            }
        }
        $patientIds = [];
        foreach ($patientList as $k => $v) {
            $patientIds[] = $v["patient_id"];
        }
        $connection = ZhyxMongo::getInstance()->connection;
        $session = $connection->startSession();
        try {
            $session->startTransaction(['session' => $session]);
            
             //根据groupId判断当前分类所属孕周还是疾病或者是自定义，如果不是孕周分组，无须弹出
            if (isset($groupInfo) && $groupInfo["platform"] === 0) {
                $r = ZhyxMongo::getInstance()->setCollection("collect_class")->updateMany(["type" => $type, "platform" => 0], ['$pull' => ['patientList' => ['patient_id' => ['$in' => $patientIds]]]], ['session' => $session]);
            }
            if ($groupId !== "-2" && $groupId !== "-1") {
                ZhyxMongo::getInstance()->setCollection("collect_class")->updateMany(["_id" => new ObjectId($groupId)], ['$push' => ['patientList' => ['$each' => $patientList]]], ['session' => $session]);
            }
            $session->commitTransaction();
         
            return true;

        } catch (\Exception $exception) {
            if ($session->getTransactionState() !== "none") {
                $session->abortTransaction();
            }
            throw new FailedException($exception->getMessage());
        }
    }


}